/*
 * @lc app=leetcode.cn id=21 lang=javascript
 *
 * [21] 合并两个有序链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var mergeTwoLists = function (l1, l2) {
  let header = new ListNode()
  let lists = header
  while (l1 || l2) {
    if (!l1) {
      lists.next = l2
      return header.next
    }

    if (!l2) {
      lists.next = l1
      return header.next
    }

    if (l1.val > l2.val) {
      lists.next = new ListNode(l2.val)
      l2 = l2.next
    } else {
      lists.next = new ListNode(l1.val)
      l1 = l1.next
    }

    lists = lists.next
  }
  return header.next
}
// @lc code=end

function ListNode(val, next) {
  this.val = val === undefined ? 0 : val
  this.next = next === undefined ? null : next
}

var l1Arr = [1, 2, 4]
var l2Arr = [1, 3, 4]

var l1 = null
var l2 = null

for (let i = l1Arr.length; i--; i >= 0) {
  l1 = new ListNode(l1Arr[i], l1)
}

for (let i = l2Arr.length; i--; i >= 0) {
  l2 = new ListNode(l2Arr[i], l2)
}

console.log(JSON.stringify(mergeTwoLists(l1, l2)))
